package com.hy.utils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by chairal on 2017/6/29.
 */
public class CookieUtils {

    /**
     * 添加cookie
     *
     * @param name
     * @param value
     * @param maxAge
     * @param response
     */
    public static void addCookies(String name, String value, int maxAge, HttpServletResponse response){
        Cookie cookie = new Cookie(name, value);
        if(maxAge > 0){
            cookie.setMaxAge(maxAge);
        }
        response.addCookie(cookie);
    }

    /**
     * 根据cookie名称删除cookie
     *
     * @param response
     * @param name
     */
    public static void delCookie(HttpServletResponse response, String name){
        Cookie cookie = new Cookie(name, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    /**
     * 根据cookie名称获得cookie值
     *
     * @param request
     * @param name
     * @return
     */
    public static String getCookies(HttpServletRequest request, String name){
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if(name.equals(cookie.getName())){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
